﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DSheet.Core.Data;
using System.Data.SqlClient;
using System.Data;
using System.Xml.Linq;

namespace DSheet.Core
{
    public class DocDefService
    {
        public static bool SaveDocDef(DBContext context, DocDef docDef)
        {
            SqlCommand command = context.DBConnection.CreateCommand();
            command.CommandText = "insert into docdef (id,code,name) values(@id,@code,@name)";
            command.Parameters.Add(new SqlParameter("@id", docDef.Id));
            command.Parameters.Add(new SqlParameter("@code", docDef.Code));
            command.Parameters.Add(new SqlParameter("@name", docDef.Name));
            if (command.ExecuteNonQuery() > 0)
            {
                return true;
            }
            return false;
        }

        public static List<DocDef> GetAllDocDef(DBContext context)
        {
            List<DocDef> datas = new List<DocDef>();

            SqlCommand command = context.DBConnection.CreateCommand();
            string sql = "select * from docdef";
            command.CommandText = sql;

            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                DocDef data = new DocDef();
                data.Id = new Guid(Convert.ToString(reader["id"]));
                data.Code = Convert.ToString(reader["code"]);
                data.Name = Convert.ToString(reader["name"]);
                datas.Add(data);
            }
            reader.Close();

            return datas;
        }

        public static DocDef GetDocDef(DBContext context, Guid docDefId)
        {
            DocDef data = null;

            SqlCommand command = context.DBConnection.CreateCommand();
            string sql = "select * from docdef where id=@id";
            command.CommandText = sql;
            command.Parameters.Add(new SqlParameter("@id", docDefId));

            SqlDataReader reader = command.ExecuteReader();
            if (reader.Read())
            {
                data = new DocDef();
                data.Id = new Guid(Convert.ToString(reader["id"]));
                data.Code = Convert.ToString(reader["code"]);
                data.Name = Convert.ToString(reader["name"]);
                reader.Close();
            }
            else
            {
                reader.Close();
                return null;
            }

            if (data != null)
            {
                command = context.DBConnection.CreateCommand();
                command.CommandText = "select * from docdim where docid=@docid order by [index]";
                command.Parameters.Add(new SqlParameter("@docid", docDefId));
                SqlDataAdapter adapter = new SqlDataAdapter(command);
                DataSet dimSet = new DataSet();
                adapter.Fill(dimSet);
                foreach (DataRow dtRow in dimSet.Tables[0].Rows)
                {
                    DocDim docDim = new DocDim();
                    docDim.Id = new Guid(Convert.ToString(dtRow["id"]));
                    docDim.DimId = new Guid(Convert.ToString(dtRow["dimid"]));
                    docDim.DimCode = Convert.ToString(dtRow["dimcode"]);
                    docDim.DimName = Convert.ToString(dtRow["dimname"]);
                    docDim.Index = Convert.ToInt32(dtRow["index"]);
                    docDim.DirIndex = Convert.ToInt32(dtRow["dirindex"]);
                    docDim.IsPageDim = Convert.ToBoolean(dtRow["ispagedim"]);
                    string direction = Convert.ToString(dtRow["direction"]);
                    if (direction.ToUpper() == "X")
                    {
                        docDim.Direction = DimDirection.X;

                        data.XDims.Add(docDim);
                    }
                    else
                    {
                        docDim.Direction = DimDirection.Y;
                        data.YDims.Add(docDim);
                    }
                }
            }

            return data;
        }

        public static bool SaveDocDims(DBContext context, DocDef doc)
        {
            doc.RefreshDimIndex();

            SqlCommand command = context.DBConnection.CreateCommand();
            command.CommandText = "delete from docdim where docid=@docid";
            command.Parameters.Add(new SqlParameter("@docid", doc.Id));
            command.ExecuteNonQuery();
            foreach (var docDim in doc.YDims)
            {
                SaveDocDim(context, doc.Id, docDim);
            }
            foreach (var docDim in doc.XDims)
            {
                SaveDocDim(context, doc.Id, docDim);
            }
            return true;
        }

        public static bool SaveDocDim(DBContext context, Guid docId, DocDim docDim)
        {
            SqlCommand command = context.DBConnection.CreateCommand();
            command.CommandText = "insert into docdim (id,docid,dimid,dimcode,dimname,[index],direction,dirindex,ispagedim) values (@id,@docid,@dimid,@dimcode,@dimname,@index,@direction,@dirindex,@ispagedim)";
            command.Parameters.Add(new SqlParameter("@id", docDim.Id));
            command.Parameters.Add(new SqlParameter("@docid", docId));
            command.Parameters.Add(new SqlParameter("@dimid", docDim.DimId));
            command.Parameters.Add(new SqlParameter("@dimcode", docDim.DimCode));
            command.Parameters.Add(new SqlParameter("@dimname", docDim.DimName));
            command.Parameters.Add(new SqlParameter("@index", docDim.Index));
            if (docDim.Direction == DimDirection.Y)
            {
                command.Parameters.Add(new SqlParameter("@direction", "Y"));
            }
            else
            {
                command.Parameters.Add(new SqlParameter("@direction", "X"));
            }
            command.Parameters.Add(new SqlParameter("@dirindex", docDim.DirIndex));
            command.Parameters.Add(new SqlParameter("@ispagedim", docDim.IsPageDim));
            if (command.ExecuteNonQuery() > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 将配置信息发布成文档模板
        /// </summary>
        /// <param name="context"></param>
        /// <param name="docDef"></param>
        /// <returns></returns>
        public bool Publish(DBContext context, Guid yearId, Guid bdId, Guid orgId, DocDef docDef)
        {
            SqlCommand command = context.DBConnection.CreateCommand();
            string sql = "update doctemplate set islatest=@islatest where defid=@defid";
            command.CommandText = sql;
            command.Parameters.Add(new SqlParameter("@islatest", false));
            command.Parameters.Add(new SqlParameter("@defid", docDef.Id));
            command.ExecuteNonQuery();

            // 插入新模板数据
            //List<DRow> yRows = yTree.Complanate();
            //List<DRow> xRows = xTree.Complanate();
            XDocument xDoc = new XDocument();
            XElement xRoot = new XElement("dt");
            xDoc.Add(xRoot);

            DocTemplate template = new DocTemplate();
            template.Id = Guid.NewGuid();
            template.BYearId = yearId;
            template.BDomainId = bdId;
            template.BOrgId = orgId;
            template.DefId = docDef.Id;
            template.Code = docDef.Code;
            template.Name = docDef.Name;
            template.IsLatest = true;
            template.Version = DateTime.Now.ToString("yyyy.MM.dd.hhmmss");
            //template.Data = xDoc.s;
            command = context.DBConnection.CreateCommand();
            string insertSql = "insert into doctemplate (id,yearid,bdid,orgid,defid,code,name,islatest,version) values (@id,@yearid,@bdid,@orgid,@defid,@code,@name,@islatest,@version)";
            command.CommandText = insertSql;
            command.Parameters.Add(new SqlParameter("@id", template.Id));
            command.Parameters.Add(new SqlParameter("@yearid", template.BYearId));
            command.Parameters.Add(new SqlParameter("@bdid", template.BDomainId));
            command.Parameters.Add(new SqlParameter("@orgid", template.BOrgId));
            command.Parameters.Add(new SqlParameter("@defid", template.DefId));
            command.Parameters.Add(new SqlParameter("@code", template.Code));
            command.Parameters.Add(new SqlParameter("@name", template.Name));
            command.Parameters.Add(new SqlParameter("@islatest", template.IsLatest));
            command.Parameters.Add(new SqlParameter("@version", template.Version));
            command.ExecuteNonQuery();

            return true;
        }

        public DocTemplate GetTemplate(DBContext context, Guid id)
        {
            DocTemplate template = null;
            SqlCommand command = context.DBConnection.CreateCommand();
            command.CommandText = "select * from doctemplate where id=@id";
            command.Parameters.Add(new SqlParameter("@id", id));
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            DataSet dimSet = new DataSet();
            adapter.Fill(dimSet);
            if(dimSet.Tables[0].Rows.Count>0)
            {
                DataRow dtRow = dimSet.Tables[0].Rows[0];
                template = new DocTemplate();
                template.Id = new Guid(Convert.ToString(dtRow["id"]));
                template.DefId = new Guid(Convert.ToString(dtRow["yearid"]));
                template.DefId = new Guid(Convert.ToString(dtRow["bdid"]));
                template.BOrgId = new Guid(Convert.ToString(dtRow["orgid"]));
                template.DefId = new Guid(Convert.ToString(dtRow["defid"]));
                template.Code = Convert.ToString(dtRow["code"]);
                template.Name = Convert.ToString(dtRow["name"]);
                template.IsLatest = Convert.ToBoolean(dtRow["islatest"]);
                template.Version = Convert.ToString(dtRow["version"]);

            }
            return template;
        }

        public List<DocTemplate> GetTemplates(DBContext context, Guid yearId, Guid bdId, Guid orgId)
        {
            List<DocTemplate> templates = new List<DocTemplate>();

            SqlCommand command = context.DBConnection.CreateCommand();
            command.CommandText = "select * from doctemplate where islatest=@islatest and yearid=@yearid and bdid=@bdid and orgid=@orgid";
            command.Parameters.Add(new SqlParameter("@islatest", true));
            command.Parameters.Add(new SqlParameter("@yearid", yearId));
            command.Parameters.Add(new SqlParameter("@bdid", bdId));
            command.Parameters.Add(new SqlParameter("@orgid", orgId));
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            DataSet dimSet = new DataSet();
            adapter.Fill(dimSet);
            foreach (DataRow dtRow in dimSet.Tables[0].Rows)
            {
                DocTemplate template = new DocTemplate();
                template.Id = new Guid(Convert.ToString(dtRow["id"]));
                template.DefId = new Guid(Convert.ToString(dtRow["yearid"]));
                template.DefId = new Guid(Convert.ToString(dtRow["bdid"]));
                template.BOrgId = new Guid(Convert.ToString(dtRow["orgid"]));
                template.DefId = new Guid(Convert.ToString(dtRow["defid"]));
                template.Code = Convert.ToString(dtRow["code"]);
                template.Name = Convert.ToString(dtRow["name"]);
                template.IsLatest = Convert.ToBoolean(dtRow["islatest"]);
                template.Version = Convert.ToString(dtRow["version"]);

                templates.Add(template);
            }
            return templates;
        }
    }
}
